package binary_search.leetcode_35;

public class SearchInsert2 {
    public static void main(String[] args) {
        int[] arr = new int[]{1,3,5,6};
        int i = searchInsert(arr, 7);
        System.out.println(i);
    }
    public static int searchInsert(int[] nums, int target) {
        //edge case
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int len = nums.length;

        //开始二分查找
        int left = 0;
        //注意：这里初始值设置为 len，表示 len 这个下标也有可能是插入元素的位置
        int right = len;

        while (left < right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] < target){
                //下一轮的搜索区间：[mid + 1, right]
                left = mid + 1;
            }else{
                //下一轮的搜索区间[left, mid]
                right = mid;
            }
        }
        //此时 left == right, 区间[left , right]只有一个元素，一定存在要插入元素的位置
        return left;
    }
}
